import { _decorator, Component, Label, Node, CCString } from 'cc';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('LocationText')
@requireComponent(Label)
export class LocationText extends Component {
    @property({ displayName: "中文(繁体)" }) cnText = "";
    @property({ displayName: "英语" }) enText = "";
    @property({ displayName: "日语" }) jpText = "";
    @property({ displayName: "韩语" }) krText = "";
    // @property({ displayName: "德语" }) DEText = "";
    // @property({ displayName: "法语" }) FRText = "";
    // @property({ displayName: "西班牙语" }) ESText = "";
    // @property({ displayName: "葡萄牙语" }) POText = "";
    // @property({ displayName: "语言强制覆盖（留空使用系统语言）" })
    public overrideLang: string = '';

    private languageMap = {
        "en": { text: 'enText' },
        "ja": { text: 'jpText' },
        "ko": { text: 'krText' },
        'zh': { text: 'cnText' },
    };

    private mLabel: Label;
    onLoad() {
        this.mLabel = this.getComponent(Label);
    }

    onEnable() {
        this.updateLabel();
    }

    private updateLabel() {
        if (!this.mLabel) return;

        // 支持手动覆盖语言（方便测试），否则使用 navigator.language 或回退到 'en'
        const rawLang = (this.overrideLang && this.overrideLang.length > 0)
            ? this.overrideLang
            : (typeof navigator !== 'undefined' ? (navigator.language || (navigator as any).userLanguage) : 'en');
        const lang = (rawLang || 'en').toString().toLowerCase();

        // 优先匹配更具体的键（例如 'zh-tw' 在 'zh' 之前）
        // 注意：this.languageMap 中的 key 可能包含大写（如 'zh-CN'），
        // 因此在比较时把 key 小写化再用 startsWith 比较，避免大小写不一致导致匹配失败。
        // 使用 Object.keys 以兼容较低的编译目标（避免 Object.entries 在某些环境不可用）
        const keys = Object.keys(this.languageMap).sort((a, b) => b.length - a.length);
        const matchedKey = keys.find(k => lang.startsWith(k.toLowerCase()));
        const map = (this.languageMap as any)[matchedKey] || (this.languageMap as any)['en'];
        const textKey = map && map.text ? map.text : 'enText';

        const content = (this as any)[textKey];
        const out = (typeof content === 'string' && content.length > 0) ? content.replace(/\$/g, "\n") : ((this as any)['enText'] || '');
        this.mLabel.string = out;
    }
}